package com.jason.www.shiro;

import com.jason.www.domain.Permissions;
import com.jason.www.domain.Roles;
import com.jason.www.domain.User;
import com.jason.www.service.RolesService;
import com.jason.www.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Cai on 2018/6/22.
 * shiro框架 自定义授权范围
 */
public class CustomRealm extends AuthorizingRealm{
    @Autowired
    UserService userService;
    @Autowired
    RolesService rolesService;

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        //通过表单接收的用户名
        String username=token.getUsername();
        if(username!=null&&!"".equals(username)){
            User user=userService.getUserByLoginName(username);
            if(user!=null){
                return new SimpleAuthenticationInfo(user.getLoginName(),user.getLoginPassword(),getName());
            }
        }
        return null;
    }

    /**
     * 用户授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录时输入的用户名
        String loginName=(String)principals.getPrimaryPrincipal();
        if(loginName == null && loginName == "") return null;

        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //进行授权角色
        Set<Roles> roles = userService.getRolesByLoginName(loginName);
        if(roles.isEmpty()) return null;
        Set<Long> rolesIdSet = new HashSet<Long>();
        for(Roles r : roles){
            authorizationInfo.addRole(r.getName());
            rolesIdSet.add(r.getId());

        }
        //进行授权权限
        Set<String> permissionsSet = new HashSet<String>();
        Set<Permissions> permissions = rolesService.getPermissionsByRolesIds(rolesIdSet);
        for(Permissions p : permissions){
            authorizationInfo.addStringPermission(p.getTheurl());
        }
        return authorizationInfo;
    }


}
